<template>
    <div class="analysis">
        <div class="top" style="padding: 6px;background-color: white">
            <a-row :gutter="10">
                <a-range-picker v-model="time" format="YYYY-MM-DD HH:mm:ss" @change="onChange">
                    <a-icon slot="suffixIcon" type="calendar"/>
                </a-range-picker>
                <a-select :filter-option="filterOption"
                          allowClear
                          show-search
                          placeholder="请选择环保编码"
                          style="width: 150px;margin-left: 6px"
                          @change="(value)=>{selectIndex=value;searchRoute()}">
                    <a-select-option v-for="(item,index) in mecnos" :key="index">
                        {{ item }}
                    </a-select-option>
                </a-select>


                <a-button :loading="loading" style="margin-left: 10px;" type="primary" @click="searchRoute">查询路线
                </a-button>
            </a-row>
        </div>


        <div id="container" :style="`height:${height}px`"></div>

        <a-row>
            <a-col offset="20" span="4">
                <a-affix v-show="visible"
                         :offset-bottom="10"
                         style="background-color: white">
                    <a-card size="small" title="轨迹回放控制">
                        <a-row :gutter="10">
                            <a-col span="12">
                                <a-button @click="startAnimation">开始动画</a-button>
                            </a-col>
                            <a-col span="12">
                                <a-button @click="pauseAnimation">暂停动画</a-button>
                            </a-col>
                        </a-row>
                        <a-row :gutter="10">
                            <a-col span="12">
                                <a-button @click="resumeAnimation">继续动画</a-button>
                            </a-col>
                            <a-col span="12">
                                <a-button @click="stopAnimation">停止动画</a-button>
                            </a-col>
                        </a-row>
                    </a-card>
                </a-affix>
            </a-col>
        </a-row>


    </div>
</template>

<script>


import AMapLoader from "@amap/amap-jsapi-loader";
import {METHOD, request, RESPONSE} from "@/utils/request";
import moment from "moment";


export default {
    name: 'Analysis',
    i18n: require('./i18n'),
    data() {
        return {
            height: document.body.clientHeight,
            lineArr: [],  // 历史路径
            marker: null, // 代表汽车的点
            visible: false, // 右下叫的按钮组是否显示
            selectIndex: undefined, // 输入的环境编码
            time: [],  // 输入的时间
            userID: null, // 用户id
            AMap: null,
            map: null,
            loading: false,
            allMecnos: [],
            mecnos: [],
        }
    },
    created() {
    },
    beforeDestroy() {
        // 销毁地图，并清空地图容器
        if (this.map != null) {
            this.map.destroy();
        }
    },
    mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        //DOM初始化完成进行地图初始化
        this.initMap();
        this.getMecnos();

        //写在mounted中,onresize事件会在页面大小被调整时触发
        window.onresize = () => {
            return (() => {
                window.screenHeight = document.body.clientHeight;
                this.height = window.screenHeight - 100;
                console.log(this.height);
            })();
        };
    },
    methods: {
        filterOption(input, option) {
            return (
                // 过滤忽略大小写
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        getMecnos() {
            request("/mechanics/getmecno", METHOD.GET, {
                id: this.userID,
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.mecnos = res.data.data;
                    this.allMecnos = res.data.data;
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },

        searchRoute() {
            if (this.selectIndex === undefined) {
                this.map.clearMap();
                this.visible = false;
                this.$message.info("你必须选择环保编码才能查询路线")
                return;
            }

            this.loading = true;

            if (this.time.length === 0) {
                // 没有选择时间，默认查询今天开始到现在的路径
                this.time[0] = moment().startOf('day')
                this.time[1] = moment();
            }

            request("/position/getAllpostBy", METHOD.GET, {
                id: this.userID,
                input: this.mecnos[this.selectIndex],
                stime: (this.time !== null && this.time.length === 2) ? moment(this.time[0]).valueOf() / 1000 : null,
                etime: (this.time !== null && this.time.length === 2) ? moment(this.time[1]).valueOf() / 1000 : null
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {

                    // 删除地图上所有的覆盖物
                    this.map.clearMap();

                    this.lineArr = res.data.data.list;

                    if (this.lineArr.length === 0) {
                        this.$message.info("该设备没有历史轨迹")
                        return;
                    }

                    // 有数据显示控制按钮组
                    this.visible = true;
                    this.$message.success(res.data.msg);


                    // 代表小车的点
                    this.marker = new this.AMap.Marker({
                        map: this.map,
                        position: this.lineArr[0],
                        icon: require("../../../assets/img/excavator.png"),
                        offset: new this.AMap.Pixel(-26, -13), // 确保图片在路线上的偏移量
                        autoRotation: true,
                        angle: -90,
                    });
                    // 绘制轨迹
                    new this.AMap.Polyline({
                        map: this.map,
                        path: this.lineArr,
                        showDir: true,
                        strokeColor: "#28F",  //线颜色
                        // strokeOpacity: 1,     //线透明度
                        strokeWeight: 6,      //线宽
                        // strokeStyle: "solid"  //线样式
                    });

                    var passedPolyline = new this.AMap.Polyline({
                        map: this.map,
                        strokeColor: "#AF5",  //线颜色
                        strokeWeight: 6,      //线宽
                    });

                    this.marker.on('moving', function (e) {
                        passedPolyline.setPath(e.passedPath);
                    });

                    this.map.setFitView();


                } else {
                    this.$message.error(res.data.msg);
                }

                // 查询结束
                this.loading = false;
            })
        },
        stopAnimation() {
            this.marker.stopMove();
        },
        resumeAnimation() {
            this.marker.resumeMove();
        },
        pauseAnimation() {
            this.marker.pauseMove();
        },
        startAnimation() {
            this.marker.moveAlong(this.lineArr, 250);
            this.map.setCenter(this.marker.getPosition(), true)
        },
        onChange(date, dateString) {
            console.log(date, dateString);
        },
        initMap() {
            AMapLoader.load({
                key: "e6ae3ad4789b73879baf6e3a442b7781",             // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "1.4.15",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: []      // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            }).then((AMap) => {
                this.AMap = AMap;
                this.map = new AMap.Map('container', {  //设置地图容器id
                    viewMode: "2D",    //是否为3D地图模式
                    zoom: 17,           //初始化地图级别
                    center: [104.065861, 30.657401],//初始化地图中心点位置
                    resizeEnable: true
                });
            }).catch(e => {
                console.log(e);
            })
        },
    }
    // components: {Trend, SalesData, HotSearch, RankingList, Bar, MiniProgress, MiniBar, MiniArea, ChartCard}
}
</script>

<style lang="less" scoped>

#container {
    padding: 0;
    margin: 0;
    width: 100%;
    height: inherit;
}

.input-card .btn {
    margin-right: 1.2rem;
    width: 9rem;
}

.input-card .btn:last-child {
    margin-right: 0;
}


.extra-wrap {
    .extra-item {
        display: inline-block;
        margin-right: 24px;

        a:not(:first-child) {
            margin-left: 24px;
        }
    }
}

@media screen and (max-width: 992px) {
    .extra-wrap .extra-item {
        display: none;
    }
}

@media screen and (max-width: 576px) {
    .extra-wrap {
        display: none;
    }
}

</style>
